package com.newtouch.springboot.examples.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * Created by summer on 2017/5/4.
 */
@Slf4j
@RestController
@RequestMapping("emailxx")
public class MailUtilTestController {
    private static String toEmail = "2197466344@qq.com";
    private static String from;
    private static JavaMailSender mailSender;
    private static TemplateEngine templateEngine;

    public MailUtilTestController( @Value("${spring.mail.username}") String from, JavaMailSender mailSender, TemplateEngine templateEngine) {
        MailUtilTestController.from = from;
        MailUtilTestController.mailSender = mailSender;
        MailUtilTestController.templateEngine = templateEngine;
    }


    @PostMapping("testSimpleMail")
    public static void testSimpleMail() {
        EmailUtil.sendSimpleMail(mailSender, from, toEmail, "test simple mail2", " hello this is simple mail....");
    }

    @PostMapping("sendTemplateMail")
    public static void sendTemplateMail() {
        //创建邮件正文
        Context context = new Context();
        context.setVariable("id", "006");
        String emailContent = templateEngine.process("emailTemplate", context);
        EmailUtil.sendHtmlMail(mailSender, from, toEmail, "主题：这是模板邮件", emailContent);
    }

    @PostMapping("testHtmlMail")
    public static void testHtmlMail() {
        String content = "<html>\n" +
                "<body>\n" +
                "    <h3 style='color:red'>hello world ! 这是一封html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        EmailUtil.sendHtmlMail(mailSender, from, toEmail, "test html mail", content);
    }

    @PostMapping("sendAttachmentsMail")
    public void sendAttachmentsMail() {
        String filePath = "D:\\IdeaProjects\\【新技术项目】\\spring-boot-mail\\src\\main\\resources\\application.properties";
        EmailUtil.sendAttachmentsMail(mailSender, from, toEmail, "主题：带附件的邮件", "有附件，请查收！", filePath);
    }

    @PostMapping("sendInlineResourceMail")
    public void sendInlineResourceMail() {
        //不能含中文
        String rscId = "aaa";
        String content = "<html><body>这是有图片的邮件：<img src='cid:" + rscId + "' ></body></html>";
        String imgPath = "D:\\IdeaProjects\\【新技术项目】\\spring-boot-mail\\src\\main\\resources\\03_close.png";
        EmailUtil.sendInlineResourceMail(mailSender, from, toEmail, "主题：这是有图片的邮件", content, imgPath, rscId);
    }


}
